package com.dong.thread.threadbasic;

import java.util.concurrent.*;

/**
 * 创建线程的5种方法
 *
 * @author by jiweidong on 2021/11/21.
 */
public class T01_HowToCreateThread {

    static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("Hello MyThread");
        }
    }

    static class MyRun implements Runnable {
        @Override
        public void run() {
            System.out.println("Hello MyRun");
        }
    }

    static class MyCall implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("Hello MyCall");
            return "success";
        }
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 第一种 继承Thread
        new MyThread().start();

        // 第二种 实现Runnable
        new Thread(new MyRun()).start();

        // 第三种 使用Lambda
        new Thread(() -> System.out.println("Hello Lambda"));

        // 第四种 使用线程池
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(() -> {
            System.out.println("Hello ThreadPool");
        });

        // 第五种 带返回值的任务执行 Callable<>
        Future<String> future = service.submit(new MyCall());
        String s = future.get();
        System.out.println(s);
        service.shutdown();

        // 补充：不用线程池来启动Callable并获取返回值的方式
        // FutureTask是将来会产生返回值的任务
        FutureTask<String> task = new FutureTask<>(new MyCall());
        Thread t = new Thread(task);
        t.start();
        System.out.println(task.get());

    }


}
